//
//  SJImageView.swift
//  下载进度
//
//  Created by app;e on 15/10/12.
//  Copyright © 2015年 world. All rights reserved.
//
//  自定义带下载进度的 UIImageView

import UIKit

 class SJImageView: UIImageView {
    
    var progress:CGFloat = 0 {
        //属性监听,当imageView的progress属性值改变, progressView的progeress属性也跟着改变
        didSet{
            if progress > 0 {
                progressView.progress = progress
            }
        }
    }
    
    //懒加载progressView
    private lazy var progressView:SJProgressView = {
        let pV = SJProgressView()
        self.addSubview(pV)
        pV.ff_Fill(self) //progressView填充整个imageView
        pV.backgroundColor = UIColor.clearColor()
        return pV
        }()
    
    //嵌套私有类,只有在SJImageView类中使用
    private class SJProgressView: UIView{
        
        //进度0.0 ~ 1
        var progress: CGFloat = 0{
            didSet{
                setNeedsDisplay() //当progress进度改变的时候,会调用drawRect重绘
            }
        }
        
        private override func drawRect(rect: CGRect) {
            //0.判断progress的值
            if progress == 0 || progress == 1 {
                return
            }
            
            //1.准备
            //半径r
            let r = min(rect.width, rect.height) * 0.4
            //圆心center
            let center = CGPoint(x: rect.width * 0.5, y: rect.height*0.5)
            //2.画圆
            let ovalRect = CGRect(x: center.x - r, y: center.y - r, width:2*r, height: 2*r)
            let path1 = UIBezierPath(ovalInRect: ovalRect)
            UIColor.whiteColor().setFill()
            path1.fill() //在progressView的中心画一个白色的圆形
            
            //3.画显示进度的圆弧
            let startAngle = CGFloat(-M_PI_2)
            let endAngle = 2 * CGFloat(M_PI) * progress + startAngle
            let path2 = UIBezierPath(arcCenter: center, radius: r, startAngle: startAngle, endAngle: endAngle, clockwise: true)
            path2.addLineToPoint(center)
            UIColor(white: 0.8, alpha: 1).setFill()
            path2.fill()
        }
    }
    
}
